# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import http
from odoo.http import request
from odoo.exceptions import AccessDenied, AccessError
from odoo import registry as registry_get

# from odoo import fields, api, SUPERUSER_ID

import random


class Csrf(http.Controller):
    @http.route('/web2/session/csrf_token', type='json', auth='user')
    def csrf_token(self):
        token = request.csrf_token()
        return token


class Test(http.Controller):
    @http.route('/web2/test', type='json', auth='none', cors='*', csrf=False)
    def test1(self, file, import_id, jsonp='callback'):
        print('hello', file, import_id)
        return "hello!"


def circular_shift(int_value, k, bit=8):
    bit_string = '{:0%db}' % bit
    bit_value = bit_string.format(int_value)  # 8 bit binary
    bit_value = bit_value[k:] + bit_value[:k]
    int_value = int(bit_value, 2)
    return int_value


def make_token(db, login, uid, password):
    k = random.randint(1, 7)
    json_list = [db, login, str(uid), password]
    json_str = '.'.join(json_list)
    a = [circular_shift(ord(ch), k) for ch in json_str]
    a = [k] + a
    a = ['{:02x}'.format(i) for i in a]
    a = ''.join(a)
    return a


def parse_token(token):
    try:
        k = int(token[0:2])
        token2 = token[2:]
        length = int(len(token2) / 2)
        chs = [int(token2[i+i:i+i+2], 16) for i in range(length)]
        chs = [circular_shift(i, -k) for i in chs]
        chs = [chr(i) for i in chs]
        chs = ''.join(chs)
        ok = chs.split('.')
        db, login, uid, password = ok
        return db, login, int(uid), password

    except KeyError:
        raise AccessDenied()

# test_token('vwat', 'apon', 6, '4373284184f3f12937766a1bb5901a58af8108e4')


def test_token(db, login, uid, password):
    token = make_token(db, login, uid, password)
    print('make_token', token)
    db, login, uid, password = parse_token(token)
    print('test_token', db, login, uid, password)


class Access(http.Controller):
    def authenticate(self, db, login, password):
        registry = registry_get(db)
        user_obj = registry['res.users']
        return user_obj.authenticate(db, login, password, {'interactive': False})

    @http.route('/web2/access/token', type='json', auth="none",  cors='*', csrf=False)
    def access_token(self, taxno, appkey, appsecret):
        # taxno  =  todo.   companys[0].vat,
        # appkey =  'vwat.apon'
        db, login = appkey.split('.')
        password = appsecret
        uid = self.authenticate(db, login, password)
        token = make_token(db, login, uid, password)
        return {
            'token': token
        }

    def check_token(self, token):
        db, login, uid_in, password = parse_token(token)
        uid = self.authenticate(db, login, password)

        if (uid != uid_in):
            raise AccessDenied()

        return db, uid


# 加密
def enctry(s):
    k = 'djq%5cu#-jeq15abgz9_i#_w=o88m!*alpbedlbat8cr74sd'
    encry_str = ""
    for i, j in zip(s, k):
        # i为字符，j为秘钥字符
        temp = str(ord(i)+ord(j))+'_'  # 加密字符 = 字符的Unicode码 + 秘钥的Unicode码
        encry_str = encry_str + temp

    return encry_str


# 解密
def dectry(p):
    k = 'djq%5cu#-jeq15abgz9_i#_w=o88m!*alpbedlbat8cr74sd'
    dec_str = ""
    for i, j in zip(p.split("_")[:-1], k):
        # i 为加密字符，j为秘钥字符
        # 解密字符 = (加密Unicode码字符 - 秘钥字符的Unicode码)的单字节字符
        temp = chr(int(i) - ord(j))
        dec_str = dec_str+temp
    return dec_str
